export const drag = {
  mounted(el: HTMLElement, binding: any) {
    let isDragging = false;
    let offsetX = 0;
    let offsetY = 0;
    let parentWidth = window.innerWidth;
    let parentHeight = window.innerHeight;
    let targetWidth = el.offsetWidth;
    let targetHeight = el.offsetHeight;
    // 鼠标按下事件处理
    const handleMouseDown = (e: MouseEvent) => {
      isDragging = true;

      // 获取首个有定位的父元素
      let parent = el.offsetParent as HTMLElement;
      if (parent) {
        parentWidth = parent.offsetWidth;
        parentHeight = parent.offsetHeight;
      }
      targetWidth = el.offsetWidth;
      targetHeight = el.offsetHeight;
      // 计算鼠标位置与元素位置的偏移量
      const computedStyle = window.getComputedStyle(el);
      const leftValue = computedStyle.left;
      const topValue = computedStyle.top;
      let left = 0;
      let top = 0;
      if (leftValue) {
        const leftStr = leftValue.replace('px', '');
        left = Number(leftStr);
      }

      if (topValue) {
        const topStr = topValue.replace('px', '');
        top = Number(topStr);
      }

      offsetX = e.clientX - left;
      offsetY = e.clientY - top;

      // 防止文本选中和拖拽图片
      e.preventDefault();

      // 触发开始拖拽回调
      if (binding.value && binding.value.onStart) {
        binding.value.onStart(e);
      }
    };

    // 鼠标移动事件处理
    const handleMouseMove = (e: MouseEvent) => {
      if (!isDragging) return;

      // 计算新位置
      let x = e.clientX - offsetX;
      let y = e.clientY - offsetY;

      // 限制拖拽范围
      if (x <= 0) x = 0;
      if (y <= 0) y = 0;

      if (x + targetWidth >= parentWidth) x = parentWidth - targetWidth;
      if (y + targetHeight >= parentHeight) y = parentHeight - targetHeight;

      // 触发拖拽中回调
      if (binding.value && binding.value.onMove) {
        binding.value.onMove({ x, y });
      } else {
        // // 应用新位置
        el.style.left = `${x}px`;
        el.style.top = `${y}px`;
      }
    };

    // 鼠标松开事件处理
    const handleMouseUp = (e: MouseEvent) => {
      if (!isDragging) return;

      isDragging = false;
      // 触发结束拖拽回调
      if (binding.value && binding.value.onEnd) {
        binding.value.onEnd(e);
      }
    };

    // 添加事件监听
    el.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    // 保存事件处理函数以便卸载时移除
    (el as any)._dragHandlers = {
      mouseDown: handleMouseDown,
      mouseMove: handleMouseMove,
      mouseUp: handleMouseUp,
    };

    // 初始样式
    el.style.cursor = 'move';
    el.style.position = 'absolute';
    // el.style.userSelect = 'none';
  },

  unmounted(el: any) {
    // 移除事件监听
    if ((el as any)._dragHandlers) {
      el.removeEventListener('mousedown', el._dragHandlers.mouseDown);
      document.removeEventListener('mousemove', el._dragHandlers.mouseMove);
      document.removeEventListener('mouseup', el._dragHandlers.mouseUp);
    }
  },
};
